using Pdf2epub.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Pdf2epub.BusinessLogic
{
    internal abstract class CapsulingServiceBase : ICapsulingServiceBase
    {
        private readonly List<BulkDisposeHelp> m_DisposeObjects = new List<BulkDisposeHelp>();

        public IDisposable Capsule()
        {
            BulkDisposeHelp capsuleObject = new BulkDisposeHelp(CapsuleCallback);
            m_DisposeObjects.Add(capsuleObject);

            CapsuleActivity();

            return capsuleObject;
        }

        protected abstract void CapsuleActivity();

        protected abstract void UnCapsuleActivity();

        private void CapsuleCallback(BulkDisposeHelp sender)
        {
            m_DisposeObjects.Remove(sender);
            if (m_DisposeObjects.Any())
                return;

            UnCapsuleActivity();
        }

        private class BulkDisposeHelp : IDisposable
        {
            private readonly SignalBulkObjectDisposedDelegate m_Callback;

            public BulkDisposeHelp(SignalBulkObjectDisposedDelegate callback)
            {
                m_Callback = callback;
            }

            public delegate void SignalBulkObjectDisposedDelegate(BulkDisposeHelp sender);

            public void Dispose()
            {
                m_Callback(this);
            }
        }
    }
}